import React, { useState } from 'react';
import { Card, Typography, Button, Modal, Select, message, Table, Tag } from 'antd';
import { useNavigate } from 'react-router-dom';

const { Title } = Typography;
const { Option } = Select;

// 模拟采购材料数据
const mockPurchaseList = [
    {
        subtotal: 141950.0,
        numbering: 'PO2023001',
        supplier: 1,
        name: '商品混凝土',
        specification: 'C30',
        quantity: 300,
        unit: '立方米',
        unitPrice: 450,
        rate: 0.05,
        other_fee: 200,
        remark: '快递费200',
        status: 5,
        purchaseTime: '2023-03-10',
        paymentTime: '2023-03-11',
    },
    {
        subtotal: 32000.0,
        numbering: 'PO2023001',
        supplier: 2,
        name: '钢筋',
        specification: 'HRB400',
        quantity: 10,
        unit: '吨',
        unitPrice: 3200,
        rate: 0.05,
        other_fee: 0,
        remark: '',
        status: 1,
        purchaseTime: '2023-03-12',
        paymentTime: '',
    },
    {
        subtotal: 2100.0,
        numbering: 'PO2023002',
        supplier: 3,
        name: '防水涂料',
        specification: '桶装',
        quantity: 20,
        unit: '桶',
        unitPrice: 105,
        rate: 0.05,
        other_fee: 100,
        remark: '含运费',
        status: 2,
        purchaseTime: '2023-03-20',
        paymentTime: '',
    },
];

const statusMean = {
    1: '审核中',
    2: '未付款',
    3: '已取消',
    4: '已完成',
    5: '已付款',
};

const mockWarehouses = [
    { id: 101, name: '主材料仓库', projectId: 1 },
    { id: 102, name: '电气仓库', projectId: 1 },
    { id: 103, name: '装饰材料仓库', projectId: 1 },
];

const Step4InboundMaterials = () => {
    const navigate = useNavigate();
    const [materials, setMaterials] = useState(mockPurchaseList);
    const [selectedMaterial, setSelectedMaterial] = useState(null);
    const [selectedWarehouse, setSelectedWarehouse] = useState(null);
    const [modalVisible, setModalVisible] = useState(false);

    // 过滤出待入库（已付款）的材料
    const waitingInboundList = materials.filter((m) => m.status === 5);

    const handleInboundClick = (record) => {
        setSelectedMaterial(record);
        setSelectedWarehouse(null);
        setModalVisible(true);
    };

    const handleConfirmInbound = () => {
        if (!selectedWarehouse) {
            message.warning('请选择一个仓库！');
            return;
        }

        setMaterials((prev) =>
            prev.map((item) =>
                item === selectedMaterial ? { ...item, status: 4, warehouse: selectedWarehouse } : item
            )
        );

        message.success(`${selectedMaterial.name} 已成功入库至 ${selectedWarehouse}`);
        setModalVisible(false);
        setSelectedMaterial(null);
    };

    const columns = [
        {
            title: '采购编号',
            dataIndex: 'numbering',
            key: 'numbering',
        },
        {
            title: '材料名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '规格',
            dataIndex: 'specification',
            key: 'specification',
        },
        {
            title: '数量',
            dataIndex: 'quantity',
            key: 'quantity',
            render: (text, record) => `${text} ${record.unit}`,
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (text) => <Tag color="blue">{statusMean[text]}</Tag>,
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Button type="primary" onClick={() => handleInboundClick(record)}>
                    入库
                </Button>
            ),
        },
    ];

    return (
        <div>
            <Title level={4}>入库材料</Title>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Typography.Paragraph style={{ marginBottom: 0 }}>
                    管理已到货的材料入库流程。
                </Typography.Paragraph>
                <Button style={{ marginRight: 20 }} type="primary" onClick={() => navigate('/inbound-management')}>
                    编辑
                </Button>
            </div>

            <div style={{ marginTop: 20 }}>
                <Card title="待入库列表" style={{ width: '100%' }}>
                    <Table
                        dataSource={waitingInboundList}
                        columns={columns}
                        rowKey={(record) => `${record.numbering}-${record.name}`}
                        pagination={false}
                    />
                    {waitingInboundList.length === 0 && (
                        <Typography.Text type="secondary">暂无待入库材料。</Typography.Text>
                    )}
                </Card>
            </div>

            <Modal
                title="选择入库仓库"
                open={modalVisible}
                onOk={handleConfirmInbound}
                onCancel={() => setModalVisible(false)}
                okText="确认入库"
                cancelText="取消"
            >
                <p>请选择要入库的仓库：</p>
                <Select
                    style={{ width: '100%' }}
                    placeholder="请选择仓库"
                    value={selectedWarehouse}
                    onChange={(value) => setSelectedWarehouse(value)}
                >
                    {mockWarehouses.map((w) => (
                        <Option key={w.id} value={w.name}>
                            {w.name}
                        </Option>
                    ))}
                </Select>
            </Modal>
        </div>
    );
};

export default Step4InboundMaterials;
